/**
 * 
 */
package com.xbang.attendance.entity.role;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToMany;

import org.apache.commons.lang.StringUtils;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;

import enumeration.ResourceType;

/**
 * 资源-权限
 * 
 * @author dev.zhang
 */
@Entity
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class Resource implements Serializable{

	/**
	 * 
	 */
	private static final long serialVersionUID = 6925336822144012507L;

	@Id
	@GeneratedValue
	private Integer id;

	/** 资源类型 */
	@Enumerated(EnumType.STRING)
	private ResourceType type;

	/** 资源值 */
	private String value;

	/** 权限 */
	@ManyToMany(mappedBy = "resources", targetEntity = Role.class, fetch = FetchType.EAGER)
	@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
	private Set<Role> roles;

	/**
	 * The default constructor
	 */
	public Resource() {

	}

	/**
	 * Get role authorities as string
	 * 
	 * @return
	 */
	public String getRoleAuthorities() {
		List<String> roleAuthorities = new ArrayList<String>();
		for (Role role : roles) {
			roleAuthorities.add(role.getName());
		}
		return StringUtils.join(roleAuthorities, ",");
	}

	/**
	 * @return the id
	 */
	public Integer getId() {
		return id;
	}

	/**
	 * @return the type
	 */
	public ResourceType getType() {
		return type;
	}

	/**
	 * @return the value
	 */
	public String getValue() {
		return value;
	}

	/**
	 * @return the roles
	 */
	public Set<Role> getRoles() {
		return roles;
	}

	/**
	 * @param id
	 *            the id to set
	 */
	public void setId(Integer id) {
		this.id = id;
	}

	/**
	 * @param type
	 *            the type to set
	 */
	public void setType(ResourceType type) {
		this.type = type;
	}

	/**
	 * @param value
	 *            the value to set
	 */
	public void setValue(String value) {
		this.value = value;
	}

	/**
	 * @param roles
	 *            the roles to set
	 */
	public void setRoles(Set<Role> roles) {
		this.roles = roles;
	}

}
